const app = getApp()
const log = t => getApp().globalData.logger.log('[util]' + t)
const logW = t => getApp().globalData.logger.warn('[util]' + t)
const CACHE_KEY_DEBUG_SETTING = 'CACHE_KEY_DEBUG_SETTING'
const CACHE_KEY_LOG_HISTORY = 'CACHE_KEY_LOG_HISTORY'
const CACHE_KEY_DOMAIN_SETTING = 'CACHE_KEY_DOMAIN_SETTING'
const CACHE_KEY_USE_YMK_CHANNEL = 'CACHE_KEY_USE_YMK_CHANNEL'

const CHINA_API_DOMAIN_URL = {
  production: 'https://app-api.youcamapi.cn',
  preview: 'https://apptest.perfectcorp.com'
}

const NON_CHINA_API_DOMAIN_URL = {
  production: 'https://app-api-01.perfectcorp.com',
  preview: 'https://apptest.perfectcorp.com'
}

let API_DOMAIN_URL = CHINA_API_DOMAIN_URL

function setData(context, param) {
  return new Promise(resolve => {
    context.setData(param, () => {
      resolve()
    })
  })
}

function getImageInfo(param) {
  return new Promise((resolve, reject) => {
    my.getImageInfo({
      ...param,
      success: res => {
        resolve(res)
      },
      fail: error => {
        reject(error)
      }
    })
  })
}

function chooseImage(param) {
  return new Promise((resolve, reject) => {
    my.chooseImage({
      ...param,
      success: res => {
        resolve(res)
      },
      fail: error => {
        reject(error)
      }
    })
  })
}

function putImageDataToCanvas(canvasContext, param) {
  return new Promise(resolve => {
    canvasContext.putImageData({
      ...param,
      success: () => {
        resolve()
      }
    })
  })
}

function toTempFilePathFromCanvas(canvasContext, param = {}) {
  return new Promise(resolve => {
    canvasContext.toTempFilePath({
      ...param,
      success: res => {
        resolve(res.filePath)
      }
    })
  })
}

function actuallyDrawOnCanvas(canvasContext, reserve = true) {
  return new Promise(resolve => {
    canvasContext.draw(reserve, () => resolve())
  })
}

function getImageDataFromCanvas(canvasContext, param = {}) {
  return new Promise(resolve => {
    canvasContext.getImageData({
      ...param,
      success: res => {
        resolve(res)
      }
    })
  })
}

function setDebugSetting(setting) {
  my.setStorage({
    key: CACHE_KEY_DEBUG_SETTING,
    data: { setting: setting }
  })
}

function setDomainSetting(setting) {
  if (setting && setting.apiDomainConfig) {
    if (setting.apiDomainConfig == 'nonchina') {
      API_DOMAIN_URL = NON_CHINA_API_DOMAIN_URL
    } else {
      API_DOMAIN_URL = CHINA_API_DOMAIN_URL
    }
  }

  my.setStorage({
    key: CACHE_KEY_DOMAIN_SETTING,
    data: { setting: setting }
  })
}

function readAppParam(options) {
  if (options.domain) {
    if (options.domain === 'nonchina') {
      API_DOMAIN_URL = NON_CHINA_API_DOMAIN_URL
    }
    app.globalData.domainSetting.apiDomainConfig = options.domain
    log('apiDomainConfig: ' + options.domain)
    setDomainSetting(app.globalData.domainSetting)
  }

  if (options.data_type) {
    if (API_DOMAIN_URL[options.data_type]) {
      app.globalData.domainSetting.apiDomainType = options.data_type
      log('apiDomainType: ' + options.data_type)
      setDomainSetting(app.globalData.domainSetting)
    }
  }
}

function setValue(key, value) {
  log('setStorage:' + key + ':' + value)
  try {
    my.setStorageSync(key, value)
  } catch (e) {
    logW('setStorageSync' + key + ':' + value + ', Fail!', e)
  }
}

function getValue(key, fallback) {
  try {
    const value = my.getStorageSync(key)
    if (value) {
      return value
    }
  } catch (e) {
    logW('getStorageSync, ' + key + ' Fail!', e)
  }
  return fallback
}

function getApiDomain() {
  return API_DOMAIN_URL[getApp().globalData.domainSetting.apiDomainType]
}

function weightVersion(ver) {
  let result = 0
  const buildNumIgnored = ver.split('.').slice(0, 3)

  buildNumIgnored.forEach((v, i) => {
    if (isNaN(parseInt(v)) || parseInt(v) >= 1000) {
      throw new Error(`Failed to weight the version number ${v} in ${ver}`)
    }
    switch (i) {
      case 0:
        return (result += parseInt(v) * 1000 * 1000)
      case 1:
        return (result += parseInt(v) * 1000)
      case 2:
        return (result += parseInt(v))
      default:
        return
    }
  })
  return result
}

function isSupportedAppVersion() {
  const systemInfo = my.getSystemInfoSync()
  if (!systemInfo || !systemInfo.version) {
    throw new Error('No system version info')
  }
  return systemInfo.platform === "iOS" ?
      weightVersion(systemInfo.version) >= weightVersion("9.13.0") :
      weightVersion(systemInfo.version) >= weightVersion("9.12.0")
}

module.exports = {
  setData,
  getImageInfo,
  chooseImage,
  putImageDataToCanvas,
  toTempFilePathFromCanvas,
  actuallyDrawOnCanvas,
  getImageDataFromCanvas,
  setDebugSetting,
  setDomainSetting,
  CACHE_KEY_DEBUG_SETTING: CACHE_KEY_DEBUG_SETTING,
  CACHE_KEY_LOG_HISTORY: CACHE_KEY_LOG_HISTORY,
  CACHE_KEY_DOMAIN_SETTING: CACHE_KEY_DOMAIN_SETTING,
  CACHE_KEY_USE_YMK_CHANNEL: CACHE_KEY_USE_YMK_CHANNEL,
  getApiDomain,
  readAppParam,
  isSupportedAppVersion
}
